<template>
    <el-form ref="formRef" :model="form" label-position="top" :inline="true" :rules="rules">
        <div class="item">
            <div class="title">客户信息</div>

            <div class="form-content">
                <el-form-item v-if="isCrm" label="投放主体">
                    <SelectRemote
                        ref="selectRemote"
                        class="select-remote"
                        :disabled="type !== '0'"
                        :target-data="form.customerDTO.deliverySubject"
                        :basic-info="{ value: 'industryCode', label: 'deliverySubject', key: 'industryCode' }"
                        @onChange="(val: any) => onCrmChange(val)"
                    >
                        <template #icon>
                            <el-icon><Search /></el-icon>
                        </template>
                    </SelectRemote>
                </el-form-item>

                <el-form-item label="客户类型" prop="customerDTO.type">
                    <el-select v-model="form.customerDTO.type" placeholder="请选择" :disabled="type !== '0' || isCrm">
                        <el-option label="企业" :value="1"></el-option>
                        <el-option label="个人" :value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item v-if="form.customerDTO.type !== ''" label="品牌名称" prop="customerDTO.brand">
                    <el-input
                        v-model="form.customerDTO.brand"
                        placeholder="搜索客户"
                        :disabled="type !== '0' || isCrm"
                    />
                </el-form-item>

                <el-form-item
                    v-if="form.customerDTO.type === 1 && !isCrm"
                    label="投放主体"
                    prop="customerDTO.deliverySubject"
                >
                    <el-input
                        v-model="form.customerDTO.deliverySubject"
                        placeholder="请输入"
                        :disabled="type !== '0' || isCrm"
                        class="ipt-icon"
                    >
                        <template #prefix>
                            <el-icon><Search /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item v-if="form.customerDTO.type === 1" label="签约主体" prop="customerDTO.signName">
                    <el-input
                        v-model="form.customerDTO.signName"
                        placeholder="请输入"
                        :disabled="type !== '0' || isCrm"
                    />
                </el-form-item>

                <el-form-item v-if="form.customerDTO.type === 2" label="签约人姓名">
                    <el-input
                        v-model="form.customerDTO.signName"
                        placeholder="搜索客户"
                        :disabled="type !== '0' || isCrm"
                    />
                </el-form-item>

                <el-form-item v-if="form.customerDTO.type !== ''" label="客户行业" prop="customerDTO.industryCode">
                    <el-select
                        v-model="form.customerDTO.industryCode"
                        placeholder="请选择"
                        :disabled="type !== '0' || isCrm"
                    >
                        <el-option
                            v-for="item in industryList1"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                        />
                    </el-select>
                </el-form-item>
            </div>
        </div>
        <div class="item mt16">
            <div class="title">制作创意</div>

            <div class="form-content">
                <el-form-item class="creat-name" label="创意名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入" :disabled="type === '1'" />
                </el-form-item>

                <el-form-item label="创意行业" prop="industryCode">
                    <el-select v-model="form.industryCode" placeholder="请选择" :disabled="type === '1'" filterable>
                        <el-option
                            v-for="item in industryList2"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="媒体类型" label-width="260px">
                    <el-select v-model="form.mediaType" placeholder="请选择" @change="onMediaTypeChange">
                        <el-option label="梯内屏" :value="1"></el-option>
                        <el-option label="梯外屏" :value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="创意时长" prop="time">
                    <el-select v-model="form.time" placeholder="请选择" :disabled="type === '1'">
                        <el-option v-for="time in timeList" :key="time" :label="`${time}s`" :value="time" />
                    </el-select>
                </el-form-item>

                <el-form-item label="屏幕类型">
                    <el-select v-model="form.screenType" placeholder="请选择" :disabled="type === '1'">
                        <el-option label="联动" :value="1"></el-option>
                        <el-option label="上屏" :value="2"></el-option>
                    </el-select>
                </el-form-item>
            </div>
        </div>
    </el-form>
    <div class="item mt16">
        <div class="title">素材规格</div>

        <!-- 梯内的上传内容 -->
        <div v-if="form.mediaType === 1" class="flex-box">
            <div class="upload-box">
                <div class="info">
                    <div class="t">上屏内容</div>
                    <xc-upload
                        ref="uploadposition1"
                        :disabled="type === '1'"
                        :limit="1"
                        accept=".avi, .mp4"   
                        :http-request="(file: File) => uploadFile(1, file,uploadposition1)"
                        tip="上传1080*1920的视频，仅支持avi、mp4格式，视频大小不能超过投放时长*0.7M"
                        @remove="handleRemove(1)"
                    ></xc-upload>
                </div>
                <div v-if="form.screenType === 1" class="info">
                    <div class="t">下屏内容</div>
                    <div class="upload">
                        <xc-upload
                            ref="uploadposition3"
                            :disabled="type === '1'"
                            :limit="1"
                            accept=".jpg"
                            :http-request="(file: File) => uploadFile(3, file,uploadposition3)"
                            :show-file-list="false"
                            :file-list="fileListDown880"
                            tip="上传1080*880的图片，仅支持jpg格式，图片大小不能超过1M"
                            @remove="handleRemove(3)"
                        ></xc-upload>
                        <div v-if="blInfo.url" class="imgUpload">
                            <div class="imgInfo">
                                <el-image
                                    style="width: 48px; height: 48px;"
                                    :src="blInfo.url"
                                    fit="fit"
                                    :preview-src-list="[blInfo.url]"
                                />
                                <span class="img-name">{{ blInfo.name }}</span>
                            </div>
                            <el-icon
                                v-if="type !== '1'"
                                @click="
                                    form.materialDtoList = form.materialDtoList.filter(
                                        (item: any) => item.position !== 3
                                    )
                                    fileListDown880 = [];
                                "
                            >
                                <DeleteFilled />
                            </el-icon>
                        </div>
                    </div>
                    <div class="upload">
                        <xc-upload
                            ref="uploadposition2"
                            :disabled="type === '1'"
                            :limit="1"
                            accept=".jpg"
                            :history-length="brInfo.url ? 1 : 0"
                            :http-request="(file: File) => uploadFile(2, file,uploadposition2)"
                            :show-file-list="false"
                            :file-list="fileListDown720"
                            tip="上传1280*720的图片，仅支持jpg格式，图片大小不能超过1M"
                            @remove="handleRemove(2)"
                        ></xc-upload>
                        <div v-if="brInfo.url" class="imgUpload">
                            <div class="imgInfo">
                                <el-image
                                    style="width: 48px; height: 48px;"
                                    :src="brInfo.url"
                                    fit="fit"
                                    :preview-src-list="[brInfo.url]"
                                />
                                <span class="img-name">{{ brInfo.name }}</span>
                            </div>
                            <el-icon
                                v-if="type !== '1'"
                                @click="
                                    form.materialDtoList = form.materialDtoList.filter(
                                        (item: any) => item.position !== 2
                                    )
                                    fileListDown720 = [];
                                "
                            >
                                <DeleteFilled />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </div>
            <div class="screen screen-inner">
                <XcScreenType
                    screen-type="inner"
                    :top="screenTopInfo"
                    :bottom="{ resourcesType: 1, src: brInfo.url }"
                />
            </div>
        </div>

        <div v-if="form.mediaType === 2" class="flex-box">
            <div class="upload-box">
                <div class="info">
                    <div class="t t_out_three">梯外三屏素材</div>
                    <div class="t">上屏内容</div>
                    <xc-upload
                        ref="uploadposition4"
                        :disabled="type === '1'"
                        :limit="1"
                        accept=".avi, .mp4"
                        :show-file-list="true"
                        :http-request="(file: File) => uploadFile(1, file,uploadposition4)"
                        tip="上传1920*1080的视频，仅支持avi、mp4格式，视频大小不能超过投放时长*0.7M"
                        @remove="handleRemove(4)"
                    ></xc-upload>
                </div>
                <div v-if="form.screenType === 1" class="info">
                    <div class="t">下屏内容</div>
                    <div class="upload">
                        <xc-upload
                            ref="uploadposition5"
                            :disabled="type === '1'"
                            :limit="1"
                            accept=".jpg"
                            :show-file-list="false"
                            :file-list="fileListDown720"
                            :http-request="(file: File) => uploadFile(22, file,uploadposition5)"
                            tip="上传1280*720的图片，仅支持jpg格式，图片大小不能超过1M"
                            @remove="handleRemove(5)"
                        ></xc-upload>
                        <div v-if="blInfo.url" class="imgUpload">
                            <div class="imgInfo">
                                <el-image
                                    style="width: 48px; height: 48px;"
                                    :src="blInfo.url"
                                    fit="fit"
                                    :preview-src-list="[blInfo.url]"
                                />
                                <span class="img-name">{{ blInfo.name }}</span>
                            </div>
                            <el-icon
                                @click="
                                    form.materialDtoList = form.materialDtoList.filter(
                                        (item: any) => item.position !== 5
                                    )
                                    fileListDown720 = [];
                                "
                            >
                                <DeleteFilled />
                            </el-icon>
                        </div>
                    </div>
                    <div class="upload">
                        <xc-upload
                            ref="uploadposition6"
                            :disabled="type === '1'"
                            :limit="1"
                            accept=".jpg"
                            :show-file-list="false"
                            :file-list="fileListDown720"
                            :http-request="(file: File) => uploadFile(2, file,uploadposition6)"
                            tip="上传1280*720的图片，仅支持jpg格式，图片大小不能超过1M"
                            @remove="handleRemove(6)"
                        ></xc-upload>
                        <div v-if="brInfo.url" class="imgUpload">
                            <div class="imgInfo">
                                <el-image
                                    style="width: 48px; height: 48px;"
                                    :src="brInfo.url"
                                    fit="fit"
                                    :preview-src-list="[brInfo.url]"
                                />
                                <span class="img-name">{{ brInfo.name }}</span>
                            </div>
                            <el-icon
                                v-if="type !== '1'"
                                @click="
                                    form.materialDtoList = form.materialDtoList.filter(
                                        (item: any) => item.position !== 6
                                    )
                                    fileListDown720 = [];
                                "
                            >
                                <DeleteFilled />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </div>
            <div class="screen screen-out">
                <XcScreenType
                    screen-type="out"
                    :top="screenTopInfo"
                    :bottom="{ resourcesType: 1, leftSrc: blInfo.url, rightSrc: brInfo.url }"
                />
            </div>
            <div class="upload-box">
                <div class="t">梯外单屏素材</div>
                <div class="t">上屏内容</div>
                <xc-upload
                    ref="uploadposition7"
                    :disabled="type === '1'"
                    :limit="1"
                    accept=".avi, .mp4"
                    :http-request="(file: File) => uploadFile(14, file,uploadposition7)"
                    :show-file-list="true"
                    tip="上传1080*1920的视频，仅支持avi、mp4格式，视频大小不能超过投放时长*0.7M"
                    @remove="handleRemove(7)"
                ></xc-upload>
            </div>
            <div class="screen screen-single">
                <XcScreenType screen-type="single" :top="outSingScreenTopInfo" />
            </div>
        </div>

        <div class="item mt16">
            <div class="title">期望创意有效期</div>
            <div class="t">创意有效期</div>
            <el-date-picker
                v-model="form.expectEffectiveTime"
                :disabled="form.id && form.auditStatus !== 2"
                type="date"
                placeholder="请选择期望创意有效期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="pickerOptions.disabledDate"
            />
        </div>
    </div>
    <div class="item mt30 ad-info">
        <div class="title">广告资质</div>
        <el-form :model="form" label-position="top" inline>
            <div class="item">
                <el-form-item label="资质类型">
                    <el-select v-model="typeInfo" placeholder="请选择" value-key="id">
                        <el-option v-for="item in adList" :key="item.id" :label="item.name" :value="item"></el-option>
                    </el-select>
                </el-form-item>
            </div>
        </el-form>
        <xc-upload
            :limit="4"
            :http-request="(file: File) => uploadFile(4, file)"
            tip="上传资质文件，支持pdf、jpg、png格式"
            accept=".jpg,.png,.pdf"
            :show-file-list="false"
            :disabled="!typeInfo.id"
            :file-list="fileListAdRes"
            @on-remove="credentials = ''"
        ></xc-upload>
        <div v-for="(item, index) in form.adQualificationDtoList" :key="index" class="imgUpload">
            <div class="imgInfo">
                <el-image
                    style="width: 48px; height: 48px;"
                    :src="isPdf(item.url) ? pdfImg : item.url"
                    fit="fit"
                    :preview-src-list="[item.url]"
                />
                <span class="img-name">{{ item.url?.substring(item.url?.lastIndexOf('/') + 1) }}</span>
            </div>
            <el-icon @click="removeImg(index)">
                <DeleteFilled />
            </el-icon>
        </div>
    </div>

    <el-row justify="end">
        <el-button @click="goManageHome">返回创意列表</el-button>
        <el-button type="primary" :loading="drawerloading" @click="submitForm">确认</el-button>
    </el-row>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineExpose, defineProps, watchEffect, computed } from 'vue';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import { ElMessage, ElMessageBox } from 'element-plus';
import xcUpload from '@x-tech/fe-pc-components/src/components/XcUpload/index.vue';
import XcScreenType from '@x-tech/fe-pc-components/src/components/XcScreenType/index.vue';
// import XcScreenType from './XcScreenType.vue';
import { getDetail } from '@/api/delivery/creativeManage';
import SelectRemote from './SelectRemote.vue';
import { Search } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import pdfImg from '@/assets/PDF@3x.png';
import pic_hint from '@/assets/pic_hint@2x.png';
import pic_hint_out from '@/assets/pic_hint_out.png';

import { checkImgInfo, getVideoMsg } from '@/utils/common';
import type { FormInstance, FormRules } from 'element-plus';
import { getQualificationConf } from '@/api/delivery/creativeManage';
import { getIndustryFirstList, getIndustrySecondList } from '@/api/delivery/customerManage';
import router from '@/router';
import { addOrUpdate } from '@/api/delivery/creativeManage';
import { useRoute } from 'vue-router';

// * 素材位置 position  1.竖版2屏（梯内） 2.下屏720（梯内） 3.下屏880（梯内）
//  4.横版三屏-三屏上屏（梯外）
//  5.横版三屏-下屏左(梯外) 6.横版三屏-下屏右(梯外) 7.竖版单屏（梯外）
const uploadposition1 = ref(null);
const uploadposition2 = ref(null);
const uploadposition3 = ref(null);
const uploadposition4 = ref(null);
const uploadposition5 = ref(null);
const uploadposition6 = ref(null);
const uploadposition7 = ref(null);


const fileListDown880 = ref([]);
const fileListDown720 = ref([]);
const fileListAdRes = ref([]);  //广告资质

const upl = new Upload(window.XCConfig.VUE_APP_ENV);
const store = useStore();
const isCrm = computed(() => store.state.userGroup.userInfo?.useCrm);
const formRef = ref<FormInstance>();
const drawerloading = ref(false);

let form = reactive<any>({
    expectEffectiveTime: '',
    mediaType: 1,
    screenType: 1,
    customerDTO: {},
    materialDtoList: [],
    adQualificationDtoList: [],
});

let pickerOptions = reactive<any>({
    disabledDate: (time: { getTime: () => number }) => {
        // 设置可选择的日期为今天之后的365天内
        const curDate = new Date().getTime();
        // 这里算出365天的毫秒数,这里使用30的平均值, 实际中应根据具体的每个月有多少天计算;
        const day = 365 * 24 * 3600 * 1000;
        const dateRegion = curDate + day;
        return time.getTime() < Date.now() - 8.64e7 || time.getTime() > dateRegion;
    },
});

const props = defineProps({
    type: {
        type: String,
        default: '0',
    },

    detail: {
        type: Object,
        default: () => {
            return reactive({});
        },
    },
});

const route = useRoute();
setTimeout(() => {
    console.log('route', route);
}, 1000);
const isEdit = !!route.params.id;

let baseInfo = ref(null);
const getBaseInfo = async () => {
    if (route.params.id) {
        baseInfo.value = await getDetail(route.params.id as string);
        console.log('baseinfo', baseInfo.value);

        Object.assign(form, baseInfo.value);
    }
};
getBaseInfo();

const timeList = ref<number[]>([]);
const typeInfo = ref<any>('');
const getTimeList = () => {
    let times = [];
    for (let i = 1; i <= 36; i++) {
        times.push(i * 5);
    }
    return times;
};

timeList.value = getTimeList();

const isPdf = (filePath: string): boolean => {
    return /^.+(\.pdf)$/.test(filePath);
};

const credentials = ref('');
const industryList1 = ref<any>([]);
const industryList2 = ref<any>([]);

const topInfo = reactive({
    name: '',
    url: '',
    showUrl: '',
});
const blInfo = reactive({
    name: '',
    url: '',
});
const brInfo = reactive({
    name: '',
    url: '',
});
// 梯外单屏的上传结果信息
const outSingInfo = reactive({
    name: '',
    url: '',
    showUrl: '',
});
const adList = ref<any>([]);

const rules = reactive<FormRules>({
    'customerDTO.brand': [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
    'customerDTO.type': [{ required: true, message: '请选择客户类型', trigger: 'change' }],
    'customerDTO.industryCode': [{ required: true, message: '请选择客户行业', trigger: 'change' }],
    'customerDTO.deliverySubject': [{ required: !isCrm.value, message: '请输入投放主体', trigger: 'change' }],
    'customerDTO.signName': [{ required: !isCrm.value, message: '请输入签约主体', trigger: 'change' }],
    name: [{ required: true, message: '请输入创意名称', trigger: 'blur' }],
    industryCode: [{ required: true, message: '请选择创意行业', trigger: 'change' }],
    time: [{ required: true, message: '请选择创意时长', trigger: 'change' }],
});

const screenTopInfo = computed(() => {
    // 如果存在转码后的视频 直接展示视频格式
    if (topInfo.showUrl) {
        return {
            resourcesType: 2,
            src: topInfo.showUrl,
        };
        // 新建和没转码成功 直接展示正在转码中的图片
    } else if (!topInfo.showUrl && !!topInfo.url) {
        if (form.mediaType === 2) {
            return {
                resourcesType: 1,
                src: pic_hint_out,
            };
        }
        return {
            resourcesType: 1,
            src: pic_hint,
        };
    }
    return {
        resourcesType: 1,
        src: '',
    };
});

const outSingScreenTopInfo = computed(() => {
    // 如果存在转码后的视频 直接展示视频格式
    if (outSingInfo.showUrl) {
        return {
            // width: 175,
            // heigth: 311, // 组件内部拼写错误
            resourcesType: 2,
            src: outSingInfo.showUrl,
        };
        // 新建和没转码成功 直接展示正在转码中的图片
    } else if (!outSingInfo.showUrl && !!outSingInfo.url) {
        return {
            // width: 175,
            // heigth: 311,
            resourcesType: 1,
            src: pic_hint,
        };
    }
    return {
        // width: 175,
        // heigth: 311,
        resourcesType: 1,
        src: '',
    };
});

const isUploading = (posInner: number, posOut: number) => {
    console.log(posInner, posOut);
    if (
        form.materialDtoList.some((item: any) => {
            console.log(item);
            return item.position === (form.mediaType === 1 ? posInner : posOut);
        })
    ) {
        ElMessage.warning('请等待当前素材上传完毕');
        return true;
    }
    return false;
};

// * 素材位置 position  1.竖版2屏（梯内） 2.下屏720（梯内） 3.下屏880（梯内）
//  4.横版三屏-三屏上屏（梯外）
//  5.横版三屏-下屏左(梯外) 6.横版三屏-下屏右(梯外) 7.竖版单屏（梯外）

const uploadFile = async (type: number, file: File, uploadIns?: any) => {
    if (uploadIns) {
        console.log(uploadIns);
        if (uploadIns.isLoading) {
            console.log('正在上传。。');
            return;
        }
    }
    if (uploadIns) {
        uploadIns.isLoading = true;
    }
    let _file: any = file;

    console.log('file',file);
    if (Array.isArray(file) && file.length) {
        _file = file[0];
    }
    try {
        // 梯内720的下屏 1280*720   梯外 三屏的下屏素材(两个都是1280*720)  校验
        // 梯内：2   梯外：左：2 右：22
        if (type === 2 || type === 22) {
            let ImgInfo: any = await checkImgInfo(_file.file);
            console.log(ImgInfo);
            if (!(ImgInfo.width === 1280 && ImgInfo.height === 720 && ImgInfo.sizeM < 1)) {
                fileListDown720.value = [];
                ElMessage.error('上传1280*720的图片，仅支持jpg格式，图片大小不能超过1M');
                return false;
            }
        }

        // 梯内880 的下屏图片校验
        if (type === 3) {
            let ImgInfo: any = await checkImgInfo(_file.file);
            if (!(ImgInfo.width === 1080 && ImgInfo.height === 880 && ImgInfo.sizeM < 1)) {

                fileListDown880.value = [];
                ElMessage.error('上传1080*880的图片，仅支持jpg格式，图片大小不能超过1M');
                return false;
            }
        }
        if (type === 4) {
            if (form.adQualificationDtoList.length > 3) {
                ElMessage.error('上传资质最多只能上传四张');
                return false;
            }
        }
        const res = await upl.uploadWithoutFilename(_file.file!, false);
        credentials.value = res;
        switch (type) {
            case 1: // topInfo ：梯内屏视频素材 梯外屏视频素材 当选梯内时就是梯内 选梯外时就是梯外
                form.materialDtoList.push({
                    type: 1,
                    url: res,
                    position: form.mediaType === 1 ? 1 : 4,
                });
                topInfo.name = _file.file.name;
                break;
            case 2: // 梯内 梯外 720 右图片
                form.materialDtoList.push({
                    type: 2,
                    url: res,
                    position: form.mediaType === 1 ? 2 : 6,
                });
                brInfo.name = _file.file.name;
                break;
            case 22: // 梯外 720左图片
                form.materialDtoList.push({
                    type: 2,
                    url: res,
                    position: 5,
                });
                blInfo.name = _file.file.name;
                break;
            case 3: // 梯内880
                form.materialDtoList.push({
                    type: 2,
                    url: res,
                    position: 3,
                });
                blInfo.name = _file.file.name;
                break;

            // 梯外单屏的素材搜集
            case 14:
                form.materialDtoList.push({
                    type: 1,
                    url: res,
                    position: 7,
                });
                outSingInfo.name = _file.file.name;
                break;
            default:
                form.adQualificationDtoList.push({
                    typeId: typeInfo.value?.id,
                    url: credentials.value,
                    typeName: typeInfo.value?.name,
                });
        }
        ElMessage.success('上传成功');
        if (uploadIns) {
            uploadIns.isLoading = false;
        }
    } catch (error) {
        ElMessage.error('上传失败');
        if (uploadIns) {
            uploadIns.isLoading = false;
        }
    } finally {
        if (uploadIns) {
            uploadIns.isLoading = false;
        }
    }
};

const handleRemove = (position: number) => {
    form.materialDtoList = form.materialDtoList.filter((item: any) => item.position !== position);
};

const removeImg = (index: number) => {
    ElMessageBox.confirm('删除资质文件', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            form.adQualificationDtoList.splice(index, 1);
            fileListAdRes.value = fileListAdRes.value.splice(index,1);
            ElMessage.success('删除成功');
        })
        .catch(() => {});
};

const remarkMargin = computed(() => (!!form.auditRemarks || !!form.auditTime ? '5px 0' : ''));

const resetObj = (obj: { [key: string]: any }) => {
    for (let key in obj) {
        obj[key] = '';
    }
};

const reset = () => {
    resetObj(topInfo);
    resetObj(blInfo);
    resetObj(brInfo);
    resetObj(outSingInfo);
};
const onMediaTypeChange = () => {
    form.materialDtoList = [];
    reset();
};
watchEffect(() => {
    if (form.materialDtoList.length) {
        topInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 1 : 4))?.url;
        topInfo.showUrl = form.materialDtoList.find(
            (item: any) => item.position === (form.mediaType === 1 ? 1 : 4)
        )?.showUrl;

        outSingInfo.url = form.materialDtoList.find((item: any) => item.position === 7)?.url;
        outSingInfo.showUrl = form.materialDtoList.find((item: any) => item.position === 7)?.showUrl;

        blInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 3 : 5))?.url;
        brInfo.url = form.materialDtoList.find((item: any) => item.position === (form.mediaType === 1 ? 2 : 6))?.url;

        topInfo.name = topInfo.name ? topInfo.name : topInfo.url?.substring(topInfo.url.lastIndexOf('/') + 1);
        outSingInfo.name = outSingInfo.name
            ? outSingInfo.name
            : outSingInfo.url?.substring(outSingInfo.url.lastIndexOf('/') + 1);

        blInfo.name = blInfo.name ? blInfo.name : blInfo.url?.substring(blInfo.url.lastIndexOf('/') + 1);
        brInfo.name = brInfo.name ? brInfo.name : brInfo.url?.substring(brInfo.url.lastIndexOf('/') + 1);
    } else {
        reset();
    }
});

const onCrmChange = (customerDTO: any) => {
    form.customerDTO.deliverySubject = customerDTO.deliverySubject;
    form.customerDTO.industryCode = customerDTO.industryCode;
    form.customerDTO.brand = customerDTO.brand;
    form.customerDTO.type = customerDTO.type;
    form.customerDTO.customerId = customerDTO.customerId;
    form.customerDTO.signName = customerDTO.signName;
};

const goManageHome = () => {
    router.push({
        name: 'creativeManage',
    });
};
const submitForm = () => {
    formRef.value.validate(async (valid: boolean, fields: boolean) => {
        if (valid) {
            const formData = form;
            if (formData.screenType === 2) {
                if (!formData.materialDtoList.length) {
                    ElMessage.warning('请选择素材');
                    return;
                }
            } else if (formData.screenType === 1) {
                if (!formData.materialDtoList.length || formData.materialDtoList.length < 3) {
                    ElMessage.warning('联动需要上传三个素材');
                    return;
                }
            }
            drawerloading.value = true;
            try {
                await addOrUpdate(form);
                ElMessage.success(isEdit ? '编辑成功' : '新增成功');
                goManageHome();
            } finally {
                drawerloading.value = false;
            }
        }
    });
};

onMounted(async () => {
    console.log('detail', props.detail);

    if (props.detail) {
        form.expectEffectiveTime = '';
        form = Object.assign(form, props.detail);
        console.log('form', form);
    }
    try {
        const data: any = await Promise.allSettled([
            getIndustryFirstList(),
            getIndustrySecondList(),
            getQualificationConf(),
        ]);
        if (data[0].status === 'fulfilled') {
            industryList1.value = data[0]?.value;
        }
        if (data[1].status === 'fulfilled') {
            industryList2.value = data[1]?.value;
        }
        if (data[2].status === 'fulfilled') {
            adList.value = data[2]?.value;
        }
    } catch (error) {
        console.log(error);
    }
});

defineExpose({
    form,
    formRef,
});
</script>

<style lang="scss" scoped>
.el-form-item {
    width: 280px;
}
.flex-box {
    display: flex;
    justify-content: flex-start;
}
.flex-box-start {
    display: flex;
}

.flex {
    flex: 1;
}

.form-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: start;
    .creat-name {
        width: 580px;
    }
}
.item {
    width: 100%;
    .title {
        font-size: 16px;
        font-weight: 700;
        color: #333;
        margin-bottom: 16px;
    }

    .t {
        font-size: 14px;
        font-weight: 400;
        color: #333;
        margin-bottom: 16px;
    }

    .upload-box {
        min-width: 260px;
        width: 260px;
        .info {
            .upload + .upload {
                margin-top: 24px;
            }
        }
        ::v-deep(.el-upload__tip) {
            width: 260px !important;
        }

        .info + .info {
            margin-top: 20px;
        }
    }

    .screen {
        margin-right: 16px;
    }
    .screen-inner {
        transform: scale(0.8, 0.8);
    }
    .screen-out {
        transform: translateX(0) scale(0.8, 0.8);
    }
    .screen-single {
        transform: translateX(0) scale(0.8, 0.8);
    }
}

.mt30 {
    margin-top: 30px;
}

.mt16 {
    margin-top: 16px;
}
.ad-info {
    width: 510px;
}
.imgUpload {
    height: 66px;
    padding: 0 15px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #d9d9d9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 15px 16px 0;

    .imgInfo {
        display: flex;
        align-items: center;

        .img-name {
            font-size: 14px;
            padding: 0 10px;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }

    .el-icon {
        cursor: pointer;
    }
}

.el-alert {
    padding: 20px;
    align-items: center;
    margin-bottom: 16px;

    ::v-deep(.el-alert__title) {
        font-size: 16px;
        font-weight: 500;
        color: #252525;
    }

    ::v-deep(.el-alert__description) {
        font-size: 14px;
        font-weight: 400;
        color: #bcbcbc;
        margin: v-bind(remarkmargin);
    }
}

::v-deep(.el-upload-list) {
    width: 260px;
}

::v-deep(.select-remote.select .el-input__inner) {
    padding-left: 31px;
}

::v-deep(.ipt-icon .el-input__prefix-inner) {
    display: flex;
    align-items: center;
}
</style>
